<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Game</title>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<canvas id="gameCanvas" width="800" height="800"></canvas>
<script>
  const canvas = document.getElementById('gameCanvas');
  const ctx = canvas.getContext('2d');
  let players = [];
  const playerOfIds = [];
  const userId = "2"; // 用户的 id
  const userName = "逆风哭"; // 用户的名称

  class Player {
    constructor(id,x, y, color) {
      this.id = id;
      this.x = x;
      this.y = y;
      this.size = 30;
      this.color = color;
    }

    draw() {
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.size, this.size);
    }

    move(keyCode) {
      switch (keyCode) {
        case 37: // Left
          this.x = Math.max(0, this.x - 10);
          break;
        case 38: // Up
          this.y = Math.max(0, this.y - 10);
          break;
        case 39: // Right
          this.x = Math.min(canvas.width - this.size, this.x + 10);
          break;
        case 40: // Down
          this.y = Math.min(canvas.height - this.size, this.y + 10);
          break;
      }
      this.draw();
    }
  }

  function createPlayer(id,x, y, color) {
    const player = new Player(id,x, y, color);
    players.push(player);
    playerOfIds.push(id);
    return player;
  }

  function clearCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  }

  function gameLoop() {
    clearCanvas();
    players.forEach(player => {
      player.draw();
    });
  }

  document.addEventListener('keydown', (event) => {
    // Assuming player1 is the first player created and player2 is the second
    if (event.keyCode >= 37 && event.keyCode <= 40) {
      sendMessage(userId,event.keyCode);
      players.filter(player => player.id === userId)[0].move(event.keyCode);
    }
  });
  setInterval(gameLoop, 1000 / 60);

  //连接服务器
  const websocket = new WebSocket("ws://192.168.28.102:7070/websocket?userId=" + userId + "&userName=" + userName);
  websocket.onmessage = event => {
    const data = JSON.parse(event.data);
    // 处理服务器发送过来的消息
    console.log('Received message:', data);
    //创建游戏对象
    if(data.type == 1){
      console.log("玩家信息数量" +  data.players.length)
      for (let i = 0; i < data.players.length; i++) {
        console.log("玩家id："+playerOfIds);
        createPlayer(data.players[i].playerId,data.players[i].pointX, data.players[i].pointY, data.players[i].color);
      }
    }
    //销毁游戏对象
    if(data.type == 2){
      console.log("玩家信息:" +  data.players.length)
      for (let i = 0; i < data.players.length; i++) {
        destroyPlayer(data.players[i].playerId)
      }
    }
    //移动游戏对象
    if(data.type == 3){
      console.log("移动;玩家信息:" +  data.players.length)
      for (let i = 0; i < data.players.length; i++) {
        players.filter(player => player.id === data.players[i].playerId)[0].move(data.players[i].keyCode)
      }
    }
  };
  //向服务器发送消息
  function sendMessage(userId,keyCode){
    const messageData = {
      playerId: userId,
      keyCode: keyCode
    };
    websocket.send(JSON.stringify(messageData),3000);
  }
  window.addEventListener('beforeunload', () => {
    // 在页面关闭前关闭 WebSocket 连接
    websocket.close();
  });
  function destroyPlayer(playId){
    players = players.filter(player => player.id !== playId);
  }
</script>
</body>
</html>
